<template>
  <BasicModal
    v-bind="$attrs"
    @ok="handleSubmint"
    okText="提交"
    @register="register"
    :loading="loading"
    :title="modalTitle"
    @visible-change="handleVisibleChange"
  >
    <div class="pt-3px pr-3px">
      <BasicForm @register="registerForm">
        <template #slotInputGroup="{ model }">
          <a-input-group compact>
            <a-form-item-rest>
              <a-select
                v-model:value="selectVal"
                style="width: 40%"
                placeholder="请选择寄存器"
                :disabled="model.tagType === 1"
              >
                <a-select-option
                  :value="item.value"
                  v-for="(item, index) in driverregesterOPtions"
                  :key="index"
                  >{{ item.label }}</a-select-option
                >
              </a-select>
            </a-form-item-rest>

            <a-input
              style="width: 60%"
              v-model:value="inputVal"
              placeholder="请输入地址"
              :disabled="model.tagType === 1"
              v-if="+addressExtend === 0"
            />
            <div v-else style="width: 60%">
              <checkAddress
                :disabled="model.tagType === 1"
                :value="inputVal"
                :isErroByVariable="isErroByVariable"
                :driveId="props.info.data.driveId"
                @check-address="handleCheckAddress"
              />
            </div>
          </a-input-group>
        </template>
      </BasicForm>
    </div>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { BasicModal, useModal } from '/@/components/Modal';
  import { computed, nextTick, ref } from 'vue';
  import { InputGroup, Select, Input, SelectOption, Form } from 'ant-design-vue';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import checkAddress from '/@/components/selectAddress/index.vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { getFormErrorMessage, checkName } from '/@/utils/index';
  import { setValueModel } from './type';

  const props = defineProps({
    info: {
      type: Object,
      default: () => {},
    },
    typeOptions: {
      type: Array,
      default: () => [],
    },
    addressExtend: [String, Number],
    driverregesterOPtions: {
      type: Array,
      default: () => [],
    },
    readWriteModeOptions: {
      type: Array,
      default: () => [],
    },
  });
  const emit = defineEmits(['submitSuccess']);
  const AInputGroup = InputGroup;
  const AInput = Input;
  const ASelect = Select;
  const AFormItemRest = Form.ItemRest;
  const ASelectOption = SelectOption;
  let isErroByVariable = ref<boolean>(false);
  let selectVal: any = ref(null);
  let inputVal = ref('');

  let modalTitle = computed(() => {
    return `${
      !props.info.data.Name ? `${props.info.type === 'batchAdd' ? '批量' : ''}新增` : '编辑'
    }`;
  });
  // 表单内容
  const schemas: FormSchema[] = [
    {
      field: 'name',
      component: 'Input',
      label: '标签名：',
      helpMessage: '总长度为200字符，一个中文等于8个字符，数字/字母/英文下划线占1个字符',
      colProps: {
        span: 24,
      },
      rules: [
        {
          required: true,
          validator: async (_rule, value) => checkName(value, '标签名'),
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'batchNum',
      component: 'InputNumber',
      label: '新增数量：',
      colProps: {
        span: 24,
      },
      ifShow: () => {
        return props.info.type === 'batchAdd';
      },
      componentProps: {
        min: 1,
      },
      defaultValue: 2,
      rules: [
        {
          required: true,
          message: '请输入新增数量',
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'tagType',
      component: 'RadioGroup',
      label: '变量分类：',
      defaultValue: 0,
      colProps: {
        span: 24,
      },
      componentProps: {
        options: [
          {
            label: '普通',
            value: 0,
          },
          {
            label: '自定义',
            value: 1,
          },
        ],
        onChange: (e) => {
          if ((e?.target?.value || e) === 1) {
            selectVal.value = null;
            inputVal.value = '';
          }

          if (['', null, undefined].indexOf(e?.target?.value || e) === -1) clearValidate();
        },
      },
      rules: [
        {
          required: true,
          validator: async (_rule, value) => {
            if (['', null, undefined].indexOf(value) >= 0) {
              /* eslint-disable-next-line */
              return Promise.reject('请选择变量分类');
            }
            return Promise.resolve();
          },
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'address',
      component: 'Input',
      slot: 'slotInputGroup',
      label: '地址：',
      colProps: {
        span: 24,
      },
      dynamicDisabled: ({ values }) => {
        return +values.tagType === 1;
      },
      rules: [
        {
          required: true,
          validator: async (_rule, value) => checkInputByAddress(value),
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'dataType',
      component: 'Select',
      label: '数据类型：',
      colProps: {
        span: 24,
      },
      componentProps: {
        options: [],
        fieldNames: { label: 'Key', value: 'Value', key: 'Value' },
      },
      rules: [
        {
          required: true,
          validator: async (_rule, value) => {
            if (['', null, undefined].indexOf(value) >= 0) {
              /* eslint-disable-next-line */
              return Promise.reject('请选择数据类型');
            }
            return Promise.resolve();
          },
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'readWriteMode',
      component: 'Select',
      label: '读写模式：',
      colProps: {
        span: 24,
      },
      defaultValue: 0,
      componentProps: {
        options: [],
        fieldNames: { label: 'Key', value: 'Value', key: 'Value' },
      },
      rules: [
        {
          required: true,
          validator: async (_rule, value) => {
            if (['', null, undefined].indexOf(value) >= 0) {
              /* eslint-disable-next-line */
              return Promise.reject('请选择读写模式');
            }
            return Promise.resolve();
          },
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'size',
      component: 'InputNumber',
      label: '长度：',
      colProps: {
        span: 24,
      },
      defaultValue: 1,
      componentProps: {},
      rules: [
        {
          required: true,
          message: '请输入长度',
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'Display',
      component: 'RadioGroup',
      label: '显示台账:',
      defaultValue: '2',
      colProps: {
        span: 24,
      },
      componentProps: {
        options: [
          {
            label: '显示',
            value: '1',
          },
          {
            label: '不显示',
            value: '2',
          },
        ],
      },
      rules: [{ required: true, message: '请选择是否显示台账', trigger: ['change', 'blur'] }],
    },
    {
      field: 'archive',
      component: 'RadioGroup',
      label: '是否归档:',
      defaultValue: '2',
      colProps: {
        span: 24,
      },
      componentProps: {
        options: [
          {
            label: '是',
            value: '1',
          },
          {
            label: '否',
            value: '2',
          },
        ],
        onChange: (e) => {
          handleAddItem(e?.target?.value || e);
        },
      },
      rules: [{ required: true, message: '请选择是否归档', trigger: ['change', 'blur'] }],
    },
    {
      field: 'Interval',
      component: 'InputNumber',
      label: '定时存储：',
      colProps: {
        span: 24,
      },
      defaultValue: 0,
      ifShow: false,
      componentProps: {},
      rules: [
        {
          required: true,
          message: '请输入定时存储',
          trigger: ['change', 'blur'],
        },
      ],
      suffix: '(毫秒)',
    },
    {
      field: 'maxNum',
      component: 'InputNumber',
      label: '最大值：',
      ifShow: ({ values }) => {
        return +values.dataType !== 11;
      },
      defaultValue: 999999999,
      colProps: {
        span: 24,
      },
      rules: [
        {
          required: true,
          message: '请输入最大值',
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'miniNum',
      component: 'InputNumber',
      label: '最小值：',
      ifShow: ({ values }) => {
        return +values.dataType !== 11;
      },
      colProps: {
        span: 24,
      },
      componentProps: {},
      defaultValue: 0,
      rules: [
        {
          required: true,
          message: '请输入最小值',
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'unit',
      component: 'Input',
      label: '单位：',
      colProps: {
        span: 24,
      },
      // rules: [
      //   {
      //     required: true,
      //     message: '请输入单位',
      //     trigger: ['change', 'blur'],
      //   },
      // ],
    },
    {
      field: 'description',
      component: 'InputTextArea',
      label: '描述：',
      colProps: {
        span: 24,
      },
      componentProps: {
        showCount: true,
        maxlength: 200,
      },
    },
  ];
  const [
    registerForm,
    { validateFields, updateSchema, setFieldsValue, resetFields, clearValidate, getFieldsValue },
  ] = useForm({
    labelWidth: 90,
    schemas: schemas,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 24,
    },
  });
  const { createMessage } = useMessage();
  const { t } = useI18n();
  const [register] = useModal();
  let loading = false;
  function handleCheckAddress(val) {
    let resList = val.val;
    let address = Array.isArray(resList) && resList.length > 0 ? resList[0].Address : '';
    if (address) {
      inputVal.value = address;
      clearValidate('address');
      isErroByVariable.value = false;
    }
  }
  function handleAddItem(type) {
    if (type === '1') {
      updateSchema({ field: 'Interval', ifShow: true });
    } else {
      updateSchema({ field: 'Interval', ifShow: false });
    }
  }
  function checkInputByAddress(_value) {
    let val = getFieldsValue();
    // if (['', null, undefined].indexOf(selectVal.value) >= 0 && +val.tagType !== 1) {
    //   return Promise.reject('请选择寄存器');
    // }
    if (['', null, undefined].indexOf(inputVal.value) >= 0 && +val.tagType !== 1) {
      return Promise.reject('请输入地址');
    }
    // if (!/^\d+(\.\d{1,2})?$/.test(inputVal.value) && +val.tagType !== 1) {
    //   return Promise.reject('只能输入数字（含小数点）');
    // }

    return Promise.resolve();
  }
  async function handleSubmint() {
    loading = true;
    try {
      let res = await validateFields();
      let params: setValueModel = {
        ...props.info.data,
        Archive: +res.archive === 1,
        Display: +res.Display === 1,
        DataType: res.dataType,
        TagType: +res.tagType,
        ReadWriteMode: res.readWriteMode,
        Size: res.size,
        Maximum: res.maxNum,
        Minimum: res.miniNum,
        Unit: res.unit,
        Address: selectVal.value ? `${selectVal.value}${inputVal.value}` : inputVal.value,
        Regester: selectVal.value,
        No: inputVal.value,
        Name: res.name,
        Description: res.description || '',
        Interval: +res.archive === 1 ? res.Interval : 0,
      };
      if (props.info.data.Name) {
        await props.info.updateTagInfo([
          props.info.data.driveId,
          props.info.data.groupId,
          props.info.data.Name,
          params,
        ]);
      } else {
        if (props.info.type === 'batchAdd') {
          await props.info.batchAddTag([
            props.info.data.driveId,
            props.info.data.groupId,
            params,
            res.batchNum,
          ]);
        } else {
          await props.info.addTagInfo([props.info.data.driveId, props.info.data.groupId, params]);
        }
      }
      createMessage.success(t('layout.setting.operatingTitle'));
      loading = false;

      emit('submitSuccess', {});
    } catch (error: any) {
      if (['', null, undefined].indexOf(error.values.inputVal) >= 0) isErroByVariable.value = true;
      loading = false;
      getFormErrorMessage(error);
    }
  }
  function handleVisibleChange(visible) {
    if (visible) {
      nextTick(() => {
        updateSchema({
          field: 'dataType',
          componentProps: {
            options: props.typeOptions,
          },
        });
        updateSchema({
          field: 'readWriteMode',
          componentProps: {
            options: props.readWriteModeOptions,
          },
        });
        if (props.info.data.Name) {
          let setValue: setValueModel = {
            archive: props.info.data.Archive ? '1' : '2',
            Display: props.info.data.Display ? '1' : '2',
            tagType: props.info.data.TagType,
            dataType: props.info.data.DataType,
            readWriteMode: props.info.data.ReadWriteMode,
            size: props.info.data.Size,
            maxNum: props.info.data.Maximum || 0,
            miniNum: props.info.data.Minimum || 0,
            unit: props.info.data.Unit || '',
            address: props.info.data.Address,
            name: props.info.data.Name,
            description: props.info.data.Description,
            Interval: props.info.data.Interval,
          };
          selectVal.value = props.info.data.Regester;
          inputVal.value = props.info.data.No;

          // handleAddItem(setValue.archive, props.info.data.Interval || 0);
          setFieldsValue(setValue);
        } else {
          if (!selectVal.value && props.driverregesterOPtions.length > 0)
            selectVal.value = props.driverregesterOPtions[0].value;
        }
      });
    } else {
      isErroByVariable.value = false;

      selectVal.value = '';
      inputVal.value = '';
      resetFields();
    }
  }
</script>

<style lang="less" scoped></style>
